package com.weetop.aklyscan.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.google.zxing.activity.CaptureActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseFragment;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.FittingDetailBean;
import com.weetop.aklyscan.bean.FittingInfo;
import com.weetop.aklyscan.bean.IntoFittingSaveBean;
import com.weetop.aklyscan.bean.IntoProductSaveBean;
import com.weetop.aklyscan.bean.ProductDetailBean;
import com.weetop.aklyscan.bean.ScanShelfCodeBean;
import com.weetop.aklyscan.bean.TransferBoxBean;
import com.weetop.aklyscan.presenter.ZxInStockPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.utils.KeyBoardUtils;
import com.weetop.aklyscan.view.ZxInStockView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;
import static com.weetop.aklyscan.utils.Constant.INTENT_EXTRA_KEY_QR_SCAN;

public class Fragment_zx_instock extends BaseFragment<ZxInStockPresent> implements ZxInStockView, CommonRecyclerAdapter.OnItemClickListener {
    private static final int HUOJIA_CODE = 12000;
    private static final int REQUEST_HUOJIA_CODE_SCAN_ONE = 22000;

    @BindView(R.id.rcy_data)
    RecyclerView rcyData;
    @BindView(R.id.rcy_data2)
    RecyclerView rcyData2;
    @BindView(R.id.bt_huojia)
    QMUIButton btHuojia;
    Unbinder unbinder;
    @BindView(R.id.order_spinner)
    AppCompatSpinner orderSpinner;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.tv_stock_name)
    EditText tvStockName;
    @BindView(R.id.tv_stock_postion)
    EditText tvStockPostion;
    @BindView(R.id.btn_zzx_scan)
    QMUIButton btnZzxScan;
    @BindView(R.id.btn_into_save)
    QMUIButton btnIntoSave;
    private CommonRecyclerAdapter<ProductDetailBean> adapter1;
    private CommonRecyclerAdapter<FittingDetailBean> adapter12;
    private CommonRecyclerAdapter<TransferBoxBean.ItemsBean> adapter2;
    // 产品类型：1产品；2配件
    private int inStockType = 1;
    private int scanType = 1;
    private String orderCode;
    private List<ProductDetailBean> productISList;
    private List<FittingDetailBean> fittingDetailBeanList;
    private ScanShelfCodeBean scanShelfCodeBean;
    private TransferBoxBean transferBoxBean;
    private List<TransferBoxBean.ItemsBean> boxItems;
    private String barcode;
    private HashMap<String, Integer> fittingMap;

    @Override
    protected ZxInStockPresent createPresenter() {
        return new ZxInStockPresent(this, mActivity);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_zx_instock, null);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        orderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                inStockType = position + 1;
                if (!TextUtils.isEmpty(orderCode)) {
                    if (inStockType == 1) {
                        mPresenter.inStockDetail01(inStockType + "", orderCode);
                    } else {
                        mPresenter.inStockDetail02(inStockType + "", orderCode);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int position) {
        mPresenter.searchList(productISList.get(position).getCode());
//        mPresenter.searchList("RYA700ACCP183600001");
    }

    @Override
    public void getInStockDetail01Success(BaseModel<List<ProductDetailBean>> o) {
        productISList = o.getData();
        if (productISList != null && productISList.size() > 0) {
            rcyData.setLayoutManager(new LinearLayoutManager(mActivity));
            adapter1 = new CommonRecyclerAdapter<ProductDetailBean>(mActivity, R.layout.item_scanout1, productISList) {
                @Override
                public void onUpdate(BaseAdapterHelper helper, ProductDetailBean item, int position) {
                    helper.setText(R.id.tv_xuhao, position + 1 + "");
                    helper.setText(R.id.tv_huopin_xinghao, item.getGoods_model());
                    helper.setText(R.id.tv_huopin_mingcheng, item.getGoods_name());
                    helper.setText(R.id.tv_huopin_leixing, "产品");
                    helper.setText(R.id.tv_yingru_zongliang, "");
                    EditText weiru = helper.getView(R.id.et_weiruzongliang);
                    weiru.setEnabled(false);
                }
            };
            adapter1.setOnItemClickListener(this);
            rcyData.setAdapter(adapter1);
        }
    }

    @Override
    public void getInStockDetail02Success(BaseModel<List<FittingDetailBean>> o) {
        fittingDetailBeanList = o.getData();
        if (fittingDetailBeanList != null && fittingDetailBeanList.size() > 0) {
            rcyData.setLayoutManager(new LinearLayoutManager(mActivity));
            adapter12 = new CommonRecyclerAdapter<FittingDetailBean>(mActivity, R.layout.item_scanout1, fittingDetailBeanList) {
                @Override
                public void onUpdate(BaseAdapterHelper helper, FittingDetailBean item, int position) {
                    helper.setText(R.id.tv_xuhao, position + 1 + "");
                    helper.setText(R.id.tv_huopin_xinghao, item.getMatter_code());
                    helper.setText(R.id.tv_huopin_mingcheng, item.getMatter_name());
                    helper.setText(R.id.tv_huopin_leixing, "配件");
                    helper.setText(R.id.tv_yingru_zongliang, item.getNumber() + "");
                    EditText weiru = helper.getView(R.id.et_weiruzongliang);
                }
            };
            rcyData.setAdapter(adapter12);
        }
    }

    @Override
    public void scanShelfCodeSuccess(BaseModel<ScanShelfCodeBean> o) {
        scanShelfCodeBean = o.getData();
        tvStockName.setText(scanShelfCodeBean.getArea_name());
        tvStockPostion.setText(scanShelfCodeBean.getArea_code());
    }

    @Override
    public void getSearchResultSuccess(BaseModel<TransferBoxBean> o) {
        transferBoxBean = o.getData();
        boxItems = transferBoxBean.getItems();
        if (boxItems != null && boxItems.size() > 0) {
            rcyData2.setLayoutManager(new LinearLayoutManager(mActivity));
            adapter2 = new CommonRecyclerAdapter<TransferBoxBean.ItemsBean>(mActivity, R.layout.item_in_wx, boxItems) {
                @Override
                public void onUpdate(BaseAdapterHelper helper, TransferBoxBean.ItemsBean item, int position) {
                    helper.setText(R.id.tv_xuhao, position + 1 + "");
                    helper.setText(R.id.tv_huopin_sn, item.getProduct_code());
                    helper.setText(R.id.tv_huopin_mingcheng, item.getProduct_name());
                    String type = item.getProduct_type() == 1 ? "产品" : "配件";
                    helper.setText(R.id.tv_huopin_leixing, type);
                    helper.setText(R.id.tv_xiangnei_shuliang, item.getNumber() + "");
                    helper.setVisible(R.id.btn_delete, View.INVISIBLE);
//                    helper.setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            adapter2.remove(item);
//                            boxItems.remove(item);
//                        }
//                    });
                }
            };
            rcyData2.setAdapter(adapter2);
            for (TransferBoxBean.ItemsBean boxItem : boxItems) {
                if (boxItem.getProduct_type() == 2) {
                    mPresenter.scanFitting(boxItem.getProduct_code());
                }
            }
        }
    }

    @Override
    public void getFittingInfoSuccess(String matter_code, BaseModel<FittingInfo> o) {
        if (fittingMap == null) {
            fittingMap = new HashMap<>();
        }
        fittingMap.put(matter_code, o.getData().getMatter_id());
    }

    @Override
    public void saveIntoKuSuccess(BaseModel<Object> o) {
        ToastUtils.showShort("入库保存成功");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_huojia, R.id.btn_zzx_scan, R.id.btn_into_save, R.id.tv_order_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_order_code:
                XPopup.get(getActivity()).asCenterList("请选择输入方式", new String[]{"扫一扫", "手动输入"},
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                if (position == 0) {
//                                    ToastUtils.showShort("扫一扫");
                                    startScanQrCode();
                                    scanType = 1;
                                } else if (position == 1) {
                                    XPopup.get(getContext()).asInputConfirm("入库凭证单编号", "请输入入库凭证单编号",
                                            new OnInputConfirmListener() {
                                                @Override
                                                public void onConfirm(String text) {
                                                    KeyBoardUtils.closeKeybord(getView());
                                                    orderCode = text.trim();
                                                    if (!TextUtils.isEmpty(orderCode)) {
                                                        tvOrderCode.setText(orderCode);
                                                        if (inStockType == 1) {
                                                            mPresenter.inStockDetail01(inStockType + "", orderCode);
                                                        } else {
                                                            mPresenter.inStockDetail02(inStockType + "", orderCode);
                                                        }
                                                    }
                                                }
                                            })
                                            .show();
                                }
                            }
                        })
                        .show();
                break;
            case R.id.bt_huojia:
                XPopup.get(getActivity()).asCenterList("请选择输入方式", new String[]{"扫一扫", "手动输入"},
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                if (position == 0) {
//                                    ToastUtils.showShort("扫一扫");
                                    startScanQrCode();
                                    scanType = 2;
                                } else if (position == 1) {
                                    XPopup.get(getContext()).asInputConfirm("货架编号", "请输入货架编号",
                                            new OnInputConfirmListener() {
                                                @Override
                                                public void onConfirm(String text) {
                                                    KeyBoardUtils.closeKeybord(getView());
                                                    String value = text.trim();
                                                    if (!TextUtils.isEmpty(value)) {
                                                        mPresenter.scanShelfCode(value);
                                                    }
                                                }
                                            })
                                            .show();
                                }
                            }
                        })
                        .show();
                break;
            case R.id.btn_zzx_scan:
                XPopup.get(getActivity()).asCenterList("请选择输入方式", new String[]{"扫一扫", "手动输入"},
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                if (position == 0) {
//                                    ToastUtils.showShort("扫一扫");
                                    startScanQrCode();
                                    scanType = 3;
                                } else if (position == 1) {
                                    XPopup.get(getContext()).asInputConfirm("中转箱编号", "请输入中转箱编号",
                                            new OnInputConfirmListener() {
                                                @Override
                                                public void onConfirm(String text) {
                                                    KeyBoardUtils.closeKeybord(getView());
                                                    String value = text.trim();
                                                    if (!TextUtils.isEmpty(value)) {
                                                        barcode = value;
                                                        mPresenter.searchList(barcode);
                                                    }
                                                }
                                            })
                                            .show();
                                }
                            }
                        })
                        .show();
                break;
            case R.id.btn_into_save:
                if (TextUtils.isEmpty(orderCode) || scanShelfCodeBean == null || transferBoxBean == null || scanShelfCodeBean.getType_id() != inStockType) {
                    ToastUtils.showShort("入库信息缺失");
                    return;
                }
                if (BaseUtils.fastClick()) {
                    if (inStockType == 1) {//产品
                        List<IntoProductSaveBean> items = new ArrayList<>();
                        for (int i = 0; i < transferBoxBean.getItems().size(); i++) {
                            TransferBoxBean.ItemsBean itemsBean = transferBoxBean.getItems().get(i);
                            if (itemsBean.getProduct_type() == 1) {
                                IntoProductSaveBean bean = new IntoProductSaveBean();
                                bean.setGoods_sn(itemsBean.getProduct_code());
                                bean.setBarcode(transferBoxBean.getBarcode());
                                items.add(bean);
                            }
                        }
                        if (items.size() > 0) {
                            String itemsString = GsonUtils.toJson(items);
                            mPresenter.intoKuSave(inStockType + "", orderCode, scanShelfCodeBean.getTier_id() + "", itemsString);
                        } else {
                            ToastUtils.showShort("无新增产品");
                        }
                    } else {// 配件
                        List<IntoFittingSaveBean> items = new ArrayList<>();
                        for (int i = 0; i < transferBoxBean.getItems().size(); i++) {
                            TransferBoxBean.ItemsBean itemsBean = transferBoxBean.getItems().get(i);
                            if (itemsBean.getProduct_type() == 2) {
                                IntoFittingSaveBean bean = new IntoFittingSaveBean();
                                Integer matter_id = fittingMap.get(itemsBean.getProduct_code());
                                bean.setMatter_id(matter_id);
                                bean.setBarcode(transferBoxBean.getBarcode());
                                items.add(bean);
                            }
                        }
                        if (items.size() > 0) {
                            String itemsString = GsonUtils.toJson(items);
                            mPresenter.intoKuSave(inStockType + "", orderCode, scanShelfCodeBean.getTier_id() + "", itemsString);
                        } else {
                            ToastUtils.showShort("无新增配件");
                        }
                    }
                }
                break;
        }
    }

    private void startScanQrCode() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            requestPermissions(new String[]{Manifest.permission.CAMERA}, HUOJIA_CODE);
            return;
        }
        // 二维码扫描
        Intent intent = new Intent(getContext(), CaptureActivity.class);
        startActivityForResult(intent, REQUEST_HUOJIA_CODE_SCAN_ONE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null) {
            return;
        }
        switch (requestCode) {
            case HUOJIA_CODE:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startScanQrCode();
                } else {        // 授权被禁止
                    ToastUtils.showShort("请至权限中心打开本应用的相机访问权限");
                }
                break;
            default:
        }
    }

    /**
     * 扫码结果回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描结果回调
        if (requestCode == REQUEST_HUOJIA_CODE_SCAN_ONE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN);
            // scanResult 就是扫描二维码得到的字符串，再次可以根据自己的逻辑编写代码
            ToastUtils.showShort("扫码结果：" + scanResult);
            mPresenter.inStockDetail01(1 + "", scanResult);
            if (!TextUtils.isEmpty(scanResult)) {
                if (scanType == 1) {
                    orderCode = scanResult;
                    tvOrderCode.setText(scanResult);
                    if (inStockType == 1) {
                        mPresenter.inStockDetail01(inStockType + "", scanResult);
                    } else {
                        mPresenter.inStockDetail02(inStockType + "", scanResult);
                    }
                } else if (scanType == 2) {
                    mPresenter.scanShelfCode(scanResult);
                } else if (scanType == 3) {
                    mPresenter.searchList(scanResult);
                }
            }
        }
    }
}
